package serialization;

import java.io.*;

//Collar2 is not serializable
public class SerializeDog2 {
	public static void main(String[] args) {
		Collar2 c = new Collar2(3);
		Dog2 d = new Dog2(c, 5);		
		
		System.out.println("before: collar size is " + d.getCollar().getCollarSize());
		
		try {
			FileOutputStream fs = new FileOutputStream("testSerDog2.ser");
			ObjectOutputStream os = new ObjectOutputStream(fs);
			os.writeObject(d);
			os.close();
		} catch (Exception e) { e.printStackTrace(); }
		
		try {
			FileInputStream fis = new FileInputStream("testSerDog2.ser");
			ObjectInputStream ois = new ObjectInputStream(fis);
			d = (Dog2)ois.readObject();
			ois.close();
		} catch (Exception e) { e.printStackTrace(); }
		
		System.out.println("after: collar size is " + d.getCollar().getCollarSize());
	}
}

class Dog2 implements Serializable {
	transient private Collar2 theCollar;	//Object references marked transient will always be reset to NULL,
											//regardless of whether they were initialized at the time of declaration in the class.
	private int dogSize;
	public Dog2(Collar2 collar, int size) {
		theCollar = collar;
		dogSize = size;
	}
	public Collar2 getCollar() { return theCollar; }
	
	private void writeObject(ObjectOutputStream os) {
		try {
			os.defaultWriteObject();
			os.writeInt(theCollar.getCollarSize());
		} catch (Exception e) { e.printStackTrace(); }
	}
	
	private void readObject(ObjectInputStream is) {
		try {
			is.defaultReadObject();
			theCollar = new Collar2(is.readInt());
		} catch (Exception e) { e.printStackTrace(); }
	}
}

class Collar2 {
	private int collarSize;
	public Collar2(int size) { collarSize = size; }
	public int getCollarSize() { return collarSize; }
}
